/**
  * <br>JAVACC DEMO 1.0<br>
  * @copy right dwusoft company All rights reserved.<br>
  * <br>
  * @Package com.apache.dict.service
*/
package com.apache.dict.service;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.apache.api.api.PlatformService;
import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.dict.entity.DataItem;
import com.apache.dict.manager.DataItemManager;
import com.apache.dict.vo.ItemListVo;
import com.apache.exception.ServiceException;
import com.apache.tools.TreeNode;

/**
  * description: 外部或子系统调用接口
  * @author Hou DaYu 创建时间：下午04:48:42
  */
public class DictServiceImpl implements PlatformService<DataItem> {

	DataItemManager dataItemManager;

	public String doService(ParamsVo vo) throws ServiceException {
		String methodKey = vo.getMethodKey();
		if ("getList".equals(methodKey)) {
			return getList(vo);
		} else if ("getTree".equals(methodKey)) {
			return getTree(vo);
		} else if ("dictDownLoad".equals(methodKey)) {
			return dictDownLoad(vo);
		}
		return "";
	}

	@Override
	public String xmlService(ParamsVo<DataItem> vo) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 数据字典的使用：下拉列表显示；下拉列表联动
	 */
	@SuppressWarnings("rawtypes")
	private String getList(ParamsVo vo) {
		JSONArray jary = new JSONArray();
		JSONObject nvo = new JSONObject();
		nvo.put("id", "");
		nvo.put("text", "--请选择--");
		jary.add(nvo);
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("ParameterMap")), "false");
		String value = String.valueOf(vo.getParams("value"));
		if (!"false".equals(mark) && Validator.isNull(value)) {
			return jary.toString();
		}
		ItemListVo item = (ItemListVo) vo.getObj();
		ParamsVo param = new ParamsVo();
		param.setObj(item);
		List<DataItem> list = dataItemManager.getList(param);
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				DataItem dit = (DataItem) list.get(i);
				if ("0".equals(dit.getItemStatus()))
					continue;
				net.sf.json.JSONObject jvo = new net.sf.json.JSONObject();
				jvo.put("id", dit.getItemValue());
				jvo.put("text", dit.getItemText());
				jary.add(jvo);
			}
		}
		return jary.toString();
	}

	/**
	 * 数据字段控件：树形列表形式
	 */
	private String getTree(ParamsVo vo) {
		String id = String.valueOf(vo.getParams("id"));//条目名称
		String value = String.valueOf(vo.getParams("value"));//条目标识
		String cateEname = String.valueOf(vo.getParams("cateEname"));
		if (Validator.isNull(id)) {
			id = "0";
		}
		String fullEname = "";
		if ("0".equals(id) && Validator.isNotNull(value)) {
			ParamsVo<DataItem> pvo = new ParamsVo<DataItem>();
			pvo.setMethodKey("checkCateEnameAndItemValue");
			pvo.setParams("cateEname", cateEname);
			pvo.setParams("itemValue", value);
			DataItem selectItem = (DataItem) dataItemManager.execute(pvo);
			if (selectItem != null) {
				fullEname = selectItem.getFullEname();
			}
		}
		ItemListVo qvo = new ItemListVo();
		qvo.setCateEname(cateEname);
		qvo.setFatherValue(id);
		qvo.setItemStatus("1");
		ParamsVo param = new ParamsVo();
		param.setObj(qvo);
		List<DataItem> list = dataItemManager.getList(param);
		JSONArray jary = new JSONArray();
		if (!Validator.isEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				DataItem ditem = list.get(i);
				if ("0".equals(ditem.getItemStatus()))
					continue;
				TreeNode tvo = itemToTreeVo(ditem);
				if (Validator.isNotNull(fullEname)) {
					//如果当前id在默认选中值的家族中，则构造树，并展开
					if (fullEname.indexOf(ditem.getItemId()) >= 0) {
						tvo = getSubTree(tvo, ditem, fullEname);
						tvo.setState("opened");
					}
				}
				jary.add(tvo);
			}
		}
		return jary.toString();
	}

	/**
	 * 下载数据字典
	 */
	@SuppressWarnings("rawtypes")
	private String dictDownLoad(ParamsVo vo) {
		String fatherId = String.valueOf(vo.getParams("fatherId"));//条目名称
		String fatherValue = String.valueOf(vo.getParams("fatherValue"));//条目标识
		String cateEname = String.valueOf(vo.getParams("cateEname"));
		JSONArray jary = new JSONArray();
		JSONObject nvo = new JSONObject();
		nvo.put("id", "");
		nvo.put("text", "--请选择--");
		jary.add(nvo);
		//如果传递了fatherValue参数，并且为空，则不取数据
		//防止诸如城市列表，都列出来
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("ParameterMap")), "false");
		if (!"false".equals(mark) && Validator.isNull(fatherValue)) {
			return jary.toString();
		}
		ItemListVo qvo = new ItemListVo();
		qvo.setCateEname(cateEname);
		qvo.setFatherValue(fatherValue);
		ParamsVo param = new ParamsVo();
		param.setObj(qvo);
		List<DataItem> list = dataItemManager.getList(param);
		if (!Validator.isEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				DataItem dit = (DataItem) list.get(i);
				if ("0".equals(dit.getItemStatus()))
					continue;
				JSONObject jvo = new JSONObject();
				jvo.put("id", dit.getItemValue());
				jvo.put("text", dit.getItemText());
				jary.add(jvo);
			}
		}
		return jary.toString();
	}

	/**
	 * DataItem对象转换成TreeNode
	 */
	private TreeNode itemToTreeVo(DataItem vo) {
		TreeNode tvo = new TreeNode();
		tvo.setChecked("checked");
		tvo.setIconCls("");
		if (vo.getSubCount() > 0) {
			tvo.setState("closed");
		} else {
			tvo.setState("opened");
		}
		tvo.setId(vo.getItemValue());
		tvo.setText(vo.getItemText());
		return tvo;
	}

	/**
	 * 取到子节点
	 */
	@SuppressWarnings("rawtypes")
	private TreeNode getSubTree(TreeNode treeNode, DataItem item, String fullEname) {
		ItemListVo qvo = new ItemListVo();
		qvo.setCateEname(item.getCateEname());
		qvo.setItemValue(item.getItemValue());
		ParamsVo vo = new ParamsVo();
		vo.setObj(item);
		List<DataItem> list = dataItemManager.getList(vo);
		List<TreeNode> children = new ArrayList<TreeNode>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				DataItem dit = list.get(i);
				if ("0".equals(dit.getItemStatus()))
					continue;
				TreeNode tvo = itemToTreeVo(dit);
				if (fullEname.indexOf(dit.getItemId()) >= 0) {
					tvo.setState("opened");
				}
				children.add(getSubTree(tvo, dit, fullEname));
			}
		}
		treeNode.setChildren(children);
		return treeNode;
	}

	public void setDataItemManager(DataItemManager dataItemManager) {
		this.dataItemManager = dataItemManager;
	}

}
